<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="topFix">
          <div class="colors">
            <div class="color">
              <span style="background: #fdd6bd"></span>
              <p>预定未付</p>
            </div>
            <div class="color">
              <span style="background: #7de2fc"></span>
              <p>已预定</p>
            </div>
            <div class="color">
              <span style="background: #c4c5c7"></span>
              <p>过期</p>
            </div>
            <div class="color">
              <span style="background: #ff9a9e"></span>
              <p>锁定</p>
            </div>
          </div>
          <div class="buttons">
            <div>
              <el-button
                :type="!btnStates.open ? 'info' : 'primary'"
                :disabled="!btnStates.open"
                style="width: 200px"
                @click="handVisible"
                >预定</el-button
              >
            </div>
            <div>
              <el-button
                :type="!btnStates.confirm ? 'info' : 'primary'"
                :disabled="!btnStates.confirm"
                style="width: 200px"
                @click="sure"
                >确认收款</el-button
              >
            </div>
            <div>
              <el-button
                :type="!btnStates.locked ? 'info' : 'primary'"
                :disabled="!btnStates.locked"
                style="width: 200px"
                @click="lock"
                >锁定</el-button
              >
            </div>
            <div>
              <el-button
                :type="!btnStates.unLocked ? 'info' : 'primary'"
                :disabled="!btnStates.unLocked"
                style="width: 200px"
                @click="nolock"
                >取消锁定</el-button
              >
            </div>
            <div>
              <el-button
                :type="!btnStates.unOpen ? 'info' : 'primary'"
                :disabled="!btnStates.unOpen"
                style="width: 200px"
                @click="noorder"
                >取消预定</el-button
              >
            </div>
          </div>
        </div>
        <div class="vertical-scroll-wrap">
          <el-button
            icon="el-icon-arrow-left"
            v-if="showPrevIcon"
            @click="prevItem"
          ></el-button>
          <div class="vertical-scroll">
            <div class="vertical-item">
              <p
                v-for="(item, index) in list"
                :class="week_index === index ? 'item1' : 'item'"
                :key="index"
                @click="handleClick(item, index)"
              >
                {{ item.day }} {{ item.week }}
              </p>
            </div>
          </div>
          <el-button
            icon="el-icon-arrow-right"
            v-if="showNextIcon"
            class="right-icon"
            @click="nextItem"
          ></el-button>
        </div>
        <div class="table_wrap" style="margin-top: 30px">
          <table class="r_table" v-cloak>
            <thead>
              <tr>
                <th v-for="(n, i) of dataAttribute" :key="i">
                  {{ n.title }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="(n, i) of tableData"
                :key="i"
                :style="i % 2 ? 'background: #fff' : 'background: #f1f6ff'"
              >
                <td :style="i % 2 ? 'background: #fff' : 'background: #f1f6ff'">
                  {{ n.startTime }}~{{ n.endTime }}
                </td>
                <td v-for="(m, j) of n.list" :key="j">
                  <div @click="moneyclick(m, i, j)" :class="getClass(m)">
                    {{ m.price }}
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </el-col>
    </el-row>
    <!-- 添加 -->
    <addItem
      :addVisible="addVisible"
      :getAddPageData="getAddPageData"
      :getAddPageData1="getAddPageData1"
      :totallist="totallist"
      :total="total"
      :preDate="form.date"
      :gymProductId="gymProductId"
      :regionId="regionId"
      :gymProductName="gymProductName"
      :gradeActiveList="gradeActiveList"
    />
  </div>
</template>
<script>
import addItem from "./add.vue";
import { getBookGround, orderPut, settingBookGround, confirm } from "@/config/api";
import { divide, plus, times } from "@/utils/tools";
export default {
  components: {
    addItem
  },
  props: {
    regionId: {
      type: Number,
      default: 0
    },
    gymProductId: {
      type: String,
      default: ""
    },
    gymProductName: {
      type: String,
      default: ""
    }
  },
  data () {
    return {
      addVisible: false,
      editList: null,
      showNextIcon: true,
      clickNum: 0,
      lastLeft: 0,
      maxClickNum: 0, // 最大点击次数
      weekInfo: [],
      week_index: 0,
      dataAttribute: [],
      form: {
        date: "",
      },
      list: [],
      tableData: [],
      totallist: [],
      gymSiteRecordList: [],
      total: 0,
      btnStates: {
        open: false,
        confirm: false,
        locked: false,
        unLocked: false,
        unOpen: false
      },
      gradeActiveList: [], // 已选中的场地
      timer: null, // 定时器
    };
  },
  computed: {
    showPrevIcon () {
      return this.clickNum > 0;
    }
  },
  watch: {
    regionId (v) {
      if (v) {
        this.getData(this.form.date, this.regionId);
      }
    }
  },
  created () {
    // .state.userInfo.id
    this.sumtime();
    let yes = this.dealTime(0)
    this.form.date = yes.date.replace(/-/g, "")
  },
  methods: {
    getClass (record) {
      if (record.disabled) {
        return "table__row__td_7"
      }
      let str = ""
      if (record.checked) {
        str = "table__row__td_2"
      } else {
        switch (record.status) {
          case "0":
            str = "table__row__td_1"
            break;
          case "1":
            str = "table__row__td_3"
            break;
          case "2":
            str = "table__row__td_4"
            break;
          case "3":
            str = "table__row__td_5"
            break;
          case "4":
            str = "table__row__td_6"
            break;
        }

      }
      return str
    },
    // 预定
    handVisible () {
      console.log(this.gradeActiveList)
      this.totallist = [];
      let sum = 0
      let state = false
      this.gradeActiveList.map(item => {
        if (item.status == 0) {
          state = true
          this.totallist.push(item)
          sum = plus(sum, item.price)
        }
      })
      if (!state) {
        this.$alert("请选择可用的预订场次");
        return false;
      }
      this.total = sum
      this.totallist = JSON.parse(JSON.stringify(this.totallist))
      this.addVisible = true;
    },
    //提交
    getAddPageData (e) {
      if (e.data) {
        orderPut(e.data).then(res => {
          if (res.data.status == 200) {
            this.getData(this.form.date, this.regionId);
            this.totallist = []
            this.$message({
              type: "success",
              message: "成功"
            });
            console.log(res.data, "添加");
          }
        });
        this.addVisible = e.state;
      } else {
        this.addVisible = e.state;
      }
    },
    //确认收款
    getAddPageData1 (e) {
      if (e.data) {
        confirm(e.data).then(res => {
          if (res.data.status == 200) {
            this.getData(this.form.date, this.regionId);
            this.totallist = []
            this.$message({
              type: "success",
              message: "成功"
            });
            console.log(res.data, "添加");
          }
        });
        this.addVisible = e.state;
      } else {
        this.addVisible = e.state;
      }
    },
    setTotal (n) {
      this.total = n
    },
    //点击表格
    moneyclick (e) {
      if (e.disabled || e.status == 4) {
        return false;
      }
      let list = []
      for (let k in this.tableData) {

        this.tableData[k].list.map(item => {
          if (item.bookId == e.bookId) {
            item.checked = !item.checked;
          }

          if (item.checked) {
            list.push(item)
          }
        });
      }
      this.btnStates = {
        open: false,
        confirm: false,
        locked: false,
        unLocked: false,
        unOpen: false
      }
      this.gradeActiveList = list
      list.map(item => {
        console.log(item)
        switch (item.status) {
          case '0':
            this.btnStates.open = true
            this.btnStates.locked = true
            break;
          case '1':
            this.btnStates.unOpen = true

            break;
          case '2':
            this.btnStates.confirm = true
            this.btnStates.unOpen = true
            break;
          case '3':
            this.btnStates.unLocked = true

            break;

        }
      })
      // this.$forceUpdate();
    },

    //确认收款
    sure () {
      let ids = []
      let arr = []
      this.gradeActiveList.map(item => {
        if (item.status == 2) {
          ids.push(item.bookId)
          if (item.relevantRecordId != null && item.relevantRecordId != 0) {
            arr.push(item.relevantRecordId)
          }
        }
      })
      if (ids.length == 0) {
        this.$alert("请选择可用的场次");
        return false;
      }
      this.$confirm('此操作将确认收款, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        settingBookGround({ operation: '1', gymSiteRecordList: ids, relevantRecordList: arr }).then(
          res => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "成功"
              });
              this.getData(this.form.date, this.regionId)
            }
          }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },
    //锁定   13694123525
    lock () {
      let ids = []
      this.gradeActiveList.map(item => {
        if (item.status == 0) {
          ids.push(item.bookId)
        }
      })
      if (ids.length == 0) {
        this.$alert("请选择可用的场次");
        return false;
      }
      this.$confirm('此操作将锁定场地, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        settingBookGround({ operation: '2', gymSiteRecordList: ids }).then(
          res => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "成功"
              });
              this.getData(this.form.date, this.regionId)
            }
          }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });


    },
    //取消锁定
    nolock () {
      let ids = []
      this.gradeActiveList.map(item => {
        if (item.status == 3) {
          ids.push(item.bookId)
        }
      })
      if (ids.length == 0) {
        this.$alert("请选择可用的场次");
        return false;
      }
      this.$confirm('此操作将取消锁定场地, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        settingBookGround({ operation: '3', gymSiteRecordList: ids }).then(
          res => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "成功"
              });
              this.getData(this.form.date, this.regionId)
            }
          }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },
    //取消预约
    noorder () {
      let ids = []
      let arr = []
      this.gradeActiveList.map(item => {
        if (item.status == 1 || item.status == 2) {
          ids.push(item.bookId)
          if (item.relevantRecordId != null && item.relevantRecordId != 0) {
            arr.push(item.relevantRecordId)
          }
        }
      })
      if (ids.length == 0) {
        this.$alert("请选择可用的场次");
        return false;
      }
      this.$confirm('此操作将取消预约场地, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        settingBookGround({ operation: '4', gymSiteRecordList: ids, relevantRecordList: arr }).then(
          res => {
            if (res.data.status == 200) {
              this.$message({
                type: "success",
                message: "成功"
              });
              this.getData(this.form.date, this.regionId)
            }
          }
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });

    },


    handleChange (e) {
      console.log(e, "eeee");
      // this.form.regionId = e.toString();
      this.getData(this.form.date, e);
    },
    datechange (e) {
      console.log(e, "容器");
      // this.form.date = e.replace(/-/g, "");
      this.getData(this.form.date, this.form.regionId);
    },
    // 计算时间
    sumtime () {
      var arr4 = [];
      for (let i = 0; i < 15; i++) {
        arr4.push(this.dealTime(i));
      }
      this.list = arr4
      console.log(this.regionId)

      this.getData(this.list[0].date, this.regionId);
    },
    handleClick (item, index) {
      this.form.date = item.date
      this.week_index = index;
      this.getData(this.form.date, this.regionId);
    },
    //获取列表
    getData (createDate, regionId) {
      this.btnStates = {
        open: false,
        confirm: false,
        locked: false,
        unLocked: false,
        unOpen: false
      }
      getBookGround({ createDate: createDate, regionId: regionId }).then(
        res => {
          if (res.data.status == 200) {
            this.getdatalist(res.data.result.listMap);
          }
        }
      );
    },
    //处理数据信息
    getdatalist (tableData) {
      if (Object.keys(tableData).length !== 0) {
        //处理当前表格中的数据
        //表格数组
        let arr = [];
        let arr1 = [];
        Object.keys(tableData)
          .sort()
          .forEach(k => {
            tableData[k].map(item => {
              item.start = item.time.slice(0, 2) + ':' + item.time.slice(2, 4)
              item.end = item.endTime.slice(0, 2) + ':' + item.endTime.slice(2, 4)
            })
            let endTime = tableData[k][0].endTime
            arr.push({
              startTime: k.slice(0, 2) + ':' + k.slice(2, 4),
              endTime: endTime.slice(0, 2) + ':' + endTime.slice(2, 4),
              list: tableData[k]
            });
          });
        //判断是否选中
        arr.map(item => {
          item.list.map(item1 => {
            item1.checked = false;
            item1.price = divide(item1.price, 100);
          });
        });
        arr[0].list.map(item => {
          arr1.push({
            title: item.siteName
          });
        });
        arr1.unshift({
          title: "时间"
        });
        this.dataAttribute = arr1;
        if (this.week_index == 0) {
          this.tableData = isDisabled(arr)
          clearInterval(this.timer)
          this.timer = setInterval(() => {
            console.log("没请定时器吗")
            this.tableData = isDisabled(arr)
          }, 10000)
        } else {
          clearInterval(this.timer)
          this.tableData = arr;
        }
      } else {
        this.tableData = [];
        this.dataAttribute = [];
      }
      function isDisabled (tableData) {
        new Date(this)
        let d = new Date();
        let h = d.getHours()
        let m = d.getMinutes()
        h = h > 9 ? h : '0' + h
        m = m > 9 ? m : '0' + m
        let time = h + ":" + m
        tableData.map(item => {
          if (time > item.endTime) {
            item.list.map(i => {
              i.disabled = true
            })
          }
        })
        return tableData
      }
    },
    //处理时间
    dealTime (num) {
      // num：未来天数
      var time = new Date(); // 获取当前时间日期
      var date = new Date(time.setDate(time.getDate() + num)).getDate(); //这里先获取日期，在按需求设置日期，最后获取需要的
      var year = time.getFullYear(); //获取年份
      var month = time.getMonth() + 1; // 获取月份
      var day = time.getDay(); //  获取星期
      switch (
      day //  格式化
      ) {
        case 0:
          day = "周日";
          break;
        case 1:
          day = "周一";
          break;
        case 2:
          day = "周二";
          break;
        case 3:
          day = "周三";
          break;
        case 4:
          day = "周四";
          break;
        case 5:
          day = "周五";
          break;
        case 6:
          day = "周六";
          break;
      }
      var obj = {
        // date: date,
        // day: month + "月" + (date < 10 ? "0" + date : date) + "日",
        day: month + "月" + date + "日",
        // month: month,
        week: day,
        date: year.toString() + (month < 10 ? "0" + month : month.toString()) + (date < 10 ? "0" + date : date.toString())
      };
      return obj; // 返回对象
    },
    addreserve () {
      this.$router.push({
        path: "/sports/reserve/add",
        query: {
          tableData: JSON.stringify(this.totallist),
          money: this.total
        }
      });
    },
    leftmove () {
      if (this.xxx < 0) {
        this.xxx += 1;
      }
    },
    rightmove () {
      if (this.xxx > -(this.itemlist.length + this.xxx)) {
        this.xxx -= 1;
      }
    },
    nextItem () {
      // 如果点击次数小于数组长度-1时，执行左滑动效果。
      if (this.clickNum < this.list.length - 1) {
        //获取当前元素宽度
        let width = document.querySelectorAll(".item")[this.clickNum]
          .offsetWidth;
        // 获取最后一个元素距离左侧距离
        let lastItemOffsetLeft = document.querySelectorAll(".item")[
          this.list.length - 1
        ].offsetLeft;
        // 获取可视区域宽度
        let lookWidth = document.querySelector(".vertical-scroll").clientWidth;
        console.log("移动前》》》", lastItemOffsetLeft, lookWidth);
        // 如果最后一个元素距离左侧的距离大于可视区域的宽度，表示最后一个元素没有出现，执行滚动效果
        if (lastItemOffsetLeft > lookWidth) {
          // 公示：滚动距离（元素的magin-left值） = 负的它自己的长度 + 上一次滑动的距离
          document.querySelector(
            ".vertical-item"
          ).style.marginLeft = `${-width + this.lastLeft - 300}px`;
          this.lastLeft = -width + this.lastLeft;
          this.clickNum += 1;
          // 记录到最后一个元素出现在可视区域时，点击次数的最大值。用于后面点击左侧箭头时判断右侧箭头的显示
          this.maxClickNum = this.clickNum;
        }

        /* 
         如果最后一个元素距离左侧的距离大于可视距离+自身的宽度，说明没有到最后一个, 显示右侧箭头，否则隐藏右侧箭头
         注意：这里要加上其自身的宽度，否则要多点击一下才会隐藏。因为点击的时候实际上最后一个元素还没有滚动，
         它距离左侧的距离是大于可视区域的（也就是说获取的是上一次点击之后，距离左侧的距离）
         所以这里要加上其自身的宽度
         看不懂的话不用管，反正加上就对了
       */
        this.showNextIcon = lastItemOffsetLeft > lookWidth + width;
      }
    },
    prevItem () {
      // 当点击次数大于0时才触发，这样当点击次数clickNum等于1的到时候，clickNum--等于0.根据计算属性的判断会隐藏掉左箭头
      if (this.clickNum > 0) {
        //获取当前元素宽度
        let width = document.querySelectorAll(".item")[this.clickNum - 1]
          .offsetWidth;
        // 公示：滚动距离（元素的magin-left值） = 它自己的长度 + 上一次滑动的距离
        document.querySelector(".vertical-item").style.marginLeft = `${width +
          this.lastLeft}px`;
        this.lastLeft = width + this.lastLeft;
        //点击次数-1
        this.clickNum--;
        if (this.clickNum < this.maxClickNum) {
          this.showNextIcon = true;
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.topFix {
  display: flex;
  justify-content: space-between;
}
.module-list-wrap {
  width: 400px;
  overflow-x: scroll;
}
.module-list li {
  font-style: normal;
  display: inline-block;
  width: 100px;
}
.buttons {
  display: flex;
  div {
    display: flex;
    width: 150px;
    margin: 15px;
  }
  // flex-direction: column;
  el-button {
    display: block;
  }
}
.time-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .tabs {
    display: flex;
    width: 2000px;
    overflow-x: hidden;
    overflow-y: hidden;
    margin: 0 20px;
    .tab {
      width: 100px;
      height: 40px;
      min-width: 90px;
      border: 1px solid #dcdfe6;
      text-align: center;
      line-height: 40px;
      margin-right: 15px;
      background: #fff;
    }
  }
}
.colors {
  display: flex;
  .color {
    display: flex;
    align-items: center;
    margin-left: 20px;
    span {
      display: block;

      width: 30px;
      height: 30px;
      border-radius: 5px;
      background: green;
      margin-right: 10px;
    }
  }
}

.vertical-scroll-wrap {
  display: flex;
  justify-content: space-around;
  align-items: center;
  .vertical-scroll {
    overflow: hidden;
    flex: 1;
    transition: all 0.3s ease;
    .vertical-item {
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
    }
  }
  .left-prev {
    padding-right: 10px;
  }
  .right-next {
    padding-left: 10px;
  }
  .left-prev,
  .right-next {
    width: 30px;
    height: 30px;
    vertical-align: middle;
  }
}
.item {
  width: 150px;
  height: 40px;
  min-width: 150px;
  border: 1px solid #dcdfe6;
  text-align: center;
  line-height: 40px;
  margin-right: 15px;
  background: #fff;
}
.item1 {
  width: 150px;
  height: 40px;
  min-width: 150px;
  border: 1px solid #dcdfe6;
  text-align: center;
  line-height: 40px;
  margin-right: 15px;
  background: #409eff;
  color: #fff;
}
.table_wrap {
  width: 100%;
  height: 600px;
  overflow: auto;
  border-bottom: 1px solid #fff;
}
.r_table > thead > tr {
  height: 50px;
}
table {
  table-layout: fixed;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  border: 0;
}

td,
th {
  width: 150px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: bold;
  /*超出长度...*/
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

thead tr th {
  position: sticky;
  top: 0;
  // background:#61dafb;
  background: #fff;
}

th:first-child,
td:first-child {
  position: sticky;
  left: 0;
  z-index: 1;
}
th:first-child {
  z-index: 1000; /*左上角单元格z-index，切记要设置，不然表格纵向横向滚动时会被该单元格右方或者下方的单元格遮挡*/
  background: #ffffff;
}
.table__row__td_2 {
  color: #fff;
  font-size: 14px;
  border: none;
  background: #1890ff;
}
.table__row__td_1 {
  font-size: 14px;
  color: #333333;
  border: none;
}
.table__row__td_1:hover {
  cursor: pointer;
  background: #1890ff;
  color: #fff;
}
// 已预定
.table__row__td_3 {
  background: #7de2fc;
  font-size: 14px;
  color: #fff;
  border: none;
}
// 预定未付款
.table__row__td_4 {
  background: #fdd6bd;
  font-size: 14px;
  color: #fff;
  border: none;
}
.table__row__td_5 {
  background: #ff9a9e;
  font-size: 14px;
  color: #fff;
}
.table__row__td_6 {
  background: #ccc;
  font-size: 14px;
  color: #dbefff;
}
.table__row__td_7 {
  background: #c4c5c7;
  font-size: 14px;
  color: #fff;
}
</style>
